<script setup lang="ts">
import { onBeforeUnmount, ref, shallowRef, onMounted, nextTick } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import type { SlateElement } from "@wangeditor/editor";
type InsertFnType = (url: string, alt?: string, href?: string) => void;

let emit = defineEmits({
  editChange: null,
});

let apiUrl: string | null = import.meta.env.DEV
  ? null
  : import.meta.env.VITE_API;

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref("");
const mode = ref("default");

const toolbarConfig = {
  excludeKeys: [
    "emotion",
    "insertLink",
    "editLink",
    "unLink",
    "viewLink",
    "fullScreen",
    "insertVideo",
    "insertTable",
    "insertImage",
    "todo",
  ],
};
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {
      server: "/api/check/uploadBlogImg",
      fieldName: "blogImg",
      maxFileSize: 1 * 1024 * 1024,
      allowedFileTypes: ["image/*"],
      headers: {
        Accept: "text/x-json",
        Authorization: localStorage.getItem("token") || "",
      },
      timeout: 5 * 1000, // 5 秒
      customInsert(res: any, insertFn: InsertFnType) {
        if (res.code == 200) {
          if (apiUrl) {
            insertFn(`${apiUrl}${res.data.url}`);
          } else {
            insertFn(`/api${res.data.url}`);
          }
        }
      },
    },
    uploadVideo: {
      server: "/api/check/uploadBlogVideo",
      fieldName: "blogVideo",
      // 单个文件的最大体积限制，默认为 10M
      maxFileSize: 5 * 1024 * 1024, // 5M
      // 最多可上传几个文件，默认为 5
      //   maxNumberOfFiles: 3,
      // 选择文件时的类型限制，默认为 ['video/*'] 。如不想限制，则设置为 []
      allowedFileTypes: ["video/*"],
      // 自定义增加 http  header
      headers: {
        Accept: "text/x-json",
        Authorization: localStorage.getItem("token") || "",
      },
      // 超时时间，默认为 30 秒
      timeout: 15 * 1000, // 15 秒
      // 自定义插入视频
      customInsert(res: any, insertFn: InsertFnType) {
        if (res.code == 200) {
          if (apiUrl) {
            insertFn("/api" + res.data.url.split(apiUrl)[1]);
          } else {
            insertFn(res.data.url);
          }
        }
      },
    },
  },
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

const handleChange = (editor: any) => {
  emit("editChange", { html: valueHtml.value, text: editor.getText() });
};
</script>    
<template>
  <div style="border: 1px solid #ddd">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
      class="Toolbar"
    />
    <Editor
      style="height: 500px; overflow-y: hidden"
      class="Editor"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onChange="handleChange"
    />
  </div>
</template>
<style lang="scss" scoped>
:deep() {
  .w-e-text {
    p {
      b {
        font-weight: bold !important;
      }
      i {
        font-style: italic !important;
      }
    }
  }
}
</style>